package co.sanduche.util;

import java.io.File;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import co.sanduche.util.LoadBitmapTask.ImageHolder;

public class LoadBitmapTask extends
		AsyncTask<ImageHolder, ImageHolder, ImageHolder> {

	private static final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(
			30);

	private Context context;
	private int width;
	private int height;

	public LoadBitmapTask(Context context, int width, int height) {
		// this(context, width, height, false);
		Log.v(getClass().getSimpleName(), "Crea tarea bitmap");
		this.context = context;
		this.width = width;
		this.height = height;
	}

	// public LoadBitmapTask(Context context, int width, int height,
	// boolean squared) {
	//
	// }

	@Override
	protected ImageHolder doInBackground(ImageHolder... params) {
		ImageHolder holder = params[0];
		holder.bitmap = cache.get(holder.path);
		if (holder.bitmap == null) {
			publishProgress(holder);

			holder.bitmap = BitmapUtils.decodeSampledBitmapFromUri(context,
					Uri.fromFile(new File(holder.path)), width, height);
		}
		cache.put(holder.path, holder.bitmap);
		Log.v(getClass().getSimpleName(), "Termina de cargar bitmap");
		return holder;
	}

	@Override
	protected void onProgressUpdate(ImageHolder... values) {
		ImageHolder holder = values[0];
		if (holder.placeHolder != null)
			holder.placeHolder.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onPostExecute(ImageHolder result) {
		if (result.placeHolder != null)
			result.placeHolder.setVisibility(View.GONE);
		result.view.setImageBitmap(result.bitmap);
		ObjectAnimator oa = ObjectAnimator
				.ofFloat(result.view, "alpha", 0f, 1f);
		oa.setInterpolator(new DecelerateInterpolator());
		oa.setDuration(150);
		oa.start();
		Log.v(getClass().getSimpleName(), "Termina de asignar bitmap");
	}

	public static class ImageHolder {
		ImageView view;
		String path;
		Bitmap bitmap;
		View placeHolder;

		public ImageHolder(ImageView view, String path) {
			this(view, path, null);
		}

		public ImageHolder(ImageView view, String path, View progressBar) {
			this.view = view;
			this.path = path;
			this.placeHolder = progressBar;
		}
	}

}
